package org.hughie.batch;

import org.hughie.api.FundApisMapping;
import org.hughie.aspect.Monitor;
import org.hughie.common.MConstants;
import org.hughie.common.SyncHandlerFactory;
import org.hughie.http.IHttpInvoker;
import org.hughie.mapper.BatchJobMapper;
import org.hughie.model.fmn.BaseFundInfoFMN;
import org.hughie.model.po.BatchJob;
import org.hughie.sync.FundSyncTask;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.ExecutorService;

/**
 * @author hughie.cheng
 * @date 2024/3/7
 */
@Component
public class BatchJobLauncher {
    private BatchJobMapper mapper;
    private SyncHandlerFactory factory;
    @Qualifier("syncThreadExecutor")
    private ExecutorService executor;
    private IHttpInvoker invoker;

    public BatchJobLauncher(BatchJobMapper mapper, SyncHandlerFactory factory, ExecutorService executor, IHttpInvoker invoker) {
        this.mapper = mapper;
        this.factory = factory;
        this.executor = executor;
        this.invoker = invoker;
    }

    @Monitor
    public void execute(String type) {
        List<BatchJob> jobs = mapper.getJobs();
        if (jobs.isEmpty()) return;
        FundSyncTask handler = factory.getHandler(type);
        handler.syncBatch(jobs);
        // jobs.forEach(t -> executor.submit(() -> handler.sync(t.getFundCode()))); 防止接口调用过快
    }

    /**
     * 基金排名列表同步接口
     */
    @Monitor
    @Deprecated
    public void initFundList() {
        long timeStamp = System.currentTimeMillis();
        for (int i = MConstants.PAGE_NO; i < 10; i++) {
            List<BaseFundInfoFMN> list = invoker.getList(FundApisMapping.FUND_RANK_LIST, String.valueOf(i), String.valueOf(MConstants.PAGE_SIZE), String.valueOf(timeStamp));
            list.forEach(t -> mapper.addJob(t.getFCODE(), t.getSHORTNAME()));
        }
    }
}
